<template>
  <div class="space-y-6">
    <!-- 基本信息 -->
    <div class="bg-white rounded-lg shadow p-6">
      <h2 class="text-lg font-medium text-gray-900 mb-4">{{ $t('profile.basicInfo') }}</h2>

      <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
          <label class="block text-sm font-medium text-gray-700">{{ $t('auth.username') }}</label>
          <p class="mt-1 text-sm text-gray-900">{{ authStore.user?.username }}</p>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700">{{ $t('auth.email') }}</label>
          <p class="mt-1 text-sm text-gray-900">{{ authStore.user?.email }}</p>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700">{{ $t('auth.phone') }}</label>
          <p class="mt-1 text-sm text-gray-900">
            {{ authStore.user?.phone_number || $t('profile.notSet') }}
          </p>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700">{{ $t('profile.registeredAt') }}</label>
          <p class="mt-1 text-sm text-gray-900">
            {{ formatDate(authStore.user?.created_at || '') }}
          </p>
        </div>
      </div>
    </div>

    <!-- 修改密码 -->
    <div class="bg-white rounded-lg shadow p-6">
      <h2 class="text-lg font-medium text-gray-900 mb-4">{{ $t('profile.changePassword') }}</h2>

      <form @submit.prevent="handleChangePassword" class="space-y-4">
        <div>
          <label for="currentPassword" class="block text-sm font-medium text-gray-700">
            {{ $t('profile.currentPassword') }}
          </label>
          <input
            id="currentPassword"
            v-model="passwordForm.currentPassword"
            type="password"
            required
            class="mt-1 input-field"
            :placeholder="$t('auth.placeholders.password')"
          />
        </div>

        <div>
          <label for="newPassword" class="block text-sm font-medium text-gray-700">
            {{ $t('profile.newPassword') }}
          </label>
          <input
            id="newPassword"
            v-model="passwordForm.newPassword"
            type="password"
            required
            minlength="6"
            class="mt-1 input-field"
            :placeholder="$t('auth.placeholders.newPassword')"
          />
        </div>

        <div>
          <label for="confirmPassword" class="block text-sm font-medium text-gray-700">
            {{ $t('profile.confirmPassword') }}
          </label>
          <input
            id="confirmPassword"
            v-model="passwordForm.confirmPassword"
            type="password"
            required
            class="mt-1 input-field"
            :placeholder="$t('auth.placeholders.confirmPassword')"
          />
        </div>

        <!-- 错误提示 -->
        <div v-if="error" class="rounded-md bg-red-50 p-4">
          <div class="flex">
            <div class="flex-shrink-0">
              <ExclamationTriangleIcon class="h-5 w-5 text-red-400" />
            </div>
            <div class="ml-3">
              <h3 class="text-sm font-medium text-red-800">
                {{ error }}
              </h3>
            </div>
          </div>
        </div>

        <!-- 成功提示 -->
        <div v-if="success" class="rounded-md bg-green-50 p-4">
          <div class="flex">
            <div class="flex-shrink-0">
              <svg class="h-5 w-5 text-green-400" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
              </svg>
            </div>
            <div class="ml-3">
              <h3 class="text-sm font-medium text-green-800">
                密码修改成功！
              </h3>
            </div>
          </div>
        </div>

        <div class="flex justify-end">
          <button
            type="submit"
            :disabled="loading"
            class="btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <span v-if="loading" class="flex items-center">
              <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
              修改中...
            </span>
            <span v-else>修改密码</span>
          </button>
        </div>
      </form>
    </div>

    <!-- 账户统计 -->
    <div class="bg-white rounded-lg shadow p-6">
      <div class="flex items-center justify-between mb-4">
        <h2 class="text-lg font-medium text-gray-900">{{ $t('profile.accountStats') }}</h2>
        <button
          @click="loadUserStats"
          :disabled="loading"
          class="text-sm text-primary-600 hover:text-primary-700 disabled:opacity-50"
        >
          {{ loading ? $t('common.loading') : $t('common.refresh') }}
        </button>
      </div>

      <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div class="text-center">
          <div class="text-2xl font-bold text-primary-600">{{ userStats.posts }}</div>
          <div class="text-sm text-gray-500">{{ $t('profile.stats.publishedPosts') }}</div>
        </div>
        <div class="text-center">
          <div class="text-2xl font-bold text-green-600">{{ userStats.sightings }}</div>
          <div class="text-sm text-gray-500">{{ $t('profile.stats.receivedSightings') }}</div>
        </div>
        <div class="text-center">
          <div class="text-2xl font-bold text-blue-600">{{ userStats.foundPets }}</div>
          <div class="text-sm text-gray-500">{{ $t('profile.stats.foundPets') }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { ExclamationTriangleIcon } from '@heroicons/vue/24/outline'
import { useAuthStore } from '@/stores/auth'
import { formatDate } from '@/utils/helpers'
import { postService } from '@/services/posts'
import { sightingService } from '@/services/sightings'

const authStore = useAuthStore()
const { t } = useI18n()

// 状态
const loading = ref(false)
const error = ref('')
const success = ref(false)

// 用户统计数据
const userStats = ref({
  posts: 0,
  sightings: 0,
  foundPets: 0
})

// 表单数据
const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: '',
})

// 计算属性
const isPasswordValid = computed(() => {
  return passwordForm.value.newPassword.length >= 6 &&
         passwordForm.value.newPassword === passwordForm.value.confirmPassword
})

// 获取用户统计数据
const loadUserStats = async () => {
  try {
    loading.value = true

    // 分批获取所有用户帖子来计算统计（因为后端限制每页最多100条）
    let allPosts: any[] = []
    let currentPage = 1
    let hasMorePages = true

    while (hasMorePages) {
      const postsResponse = await postService.getMyPosts({ page: currentPage, limit: 100 })

      if (postsResponse.success && postsResponse.data) {
        allPosts = allPosts.concat(postsResponse.data)

        // 检查是否还有更多页面
        if ('pagination' in postsResponse) {
          const pagination = (postsResponse as any).pagination
          userStats.value.posts = pagination.totalItems || 0
          hasMorePages = currentPage < pagination.totalPages
          currentPage++
        } else {
          hasMorePages = false
        }
      } else {
        hasMorePages = false
      }
    }

    // 计算找回的宠物数量（状态为found的帖子）
    const foundPosts = allPosts.filter((post: any) => post.post_status === 'found')
    const closedPosts = allPosts.filter((post: any) => post.post_status === 'closed')

    console.log('所有帖子:', allPosts.length) // 调试信息
    console.log('已找到的帖子:', foundPosts.length) // 调试信息
    console.log('已关闭的帖子:', closedPosts.length) // 调试信息
    console.log('帖子状态分布:', allPosts.map(p => ({ id: p.id, status: p.post_status, name: p.pet?.name }))) // 调试信息

    userStats.value.foundPets = foundPosts.length

    // 暂时设置线索数量为0，因为需要后端API支持
    // TODO: 实现获取用户收到的线索总数的API
    userStats.value.sightings = 0
  } catch (error) {
    console.error('获取用户统计数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 方法
const handleChangePassword = async () => {
  error.value = ''
  success.value = false

  // 验证表单
  if (!passwordForm.value.currentPassword) {
    error.value = '请输入当前密码'
    return
  }

  if (passwordForm.value.newPassword.length < 6) {
    error.value = '新密码至少需要6个字符'
    return
  }

  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    error.value = '两次输入的密码不一致'
    return
  }

  try {
    loading.value = true

    const result = await authStore.changePassword(
      passwordForm.value.currentPassword,
      passwordForm.value.newPassword
    )

    if (result) {
      success.value = true
      // 清空表单
      passwordForm.value = {
        currentPassword: '',
        newPassword: '',
        confirmPassword: '',
      }

      // 3秒后隐藏成功提示
      setTimeout(() => {
        success.value = false
      }, 3000)
    } else {
      error.value = authStore.error || '修改密码失败'
    }
  } catch (err: any) {
    error.value = err.message || '修改密码失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载统计数据
onMounted(() => {
  loadUserStats()
})
</script>
